package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.api.User.IUserClient;
import com.heima.common.cache.CacheService;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.enums.FansLevelEnum;
import com.heima.model.user.enums.FollowerLevelEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.UserRelationService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import static com.heima.user.interceptor.TokenInterceptor.THREADLOCAL;

@Service
@Transactional
public class UserRelationServiceImpl implements UserRelationService {
    @Autowired
    ApUserFanMapper apUserFanMapper;
    @Autowired
    ApUserFollowMapper apUserFollowMapper;
    @Autowired
    ApUserMapper apUserMapper;
    @Autowired
    CacheService cacheService;
    public final static Short yes=(short) 0;
    public final static Short no=(short) 1;
    @Override
    public ResponseResult saveUserRelation(UserRelationDto userRelationDto) {
        //文章id
        Long articleId = userRelationDto.getArticleId();
        //文章作者id
        Integer authorId = userRelationDto.getAuthorId();
        //操作0关注 1取关
        Integer operation = userRelationDto.getOperation();
        //当前用户id
        Integer user = Integer.parseInt(THREADLOCAL.get());
        //  查询当前用户
        ApUser apUser = apUserMapper.selectById(user);

//        //缓存中保存人物关系
//        switch (operation){
//            case 0:
//                //如果没有关注则创建key
//                if(!cacheService.hExists(String.valueOf(authorId),String.valueOf(user))){
//                    cacheService.hPut(String.valueOf(authorId),String.valueOf(user),"1");
//            } break;
//            case 1:
//                cacheService.hDelete(String.valueOf(authorId),String.valueOf(user));
//        }

        if(operation==0){
            //查询判断是否已经关注
            LambdaQueryWrapper<ApUserFan> apUserFanLambdaQueryWrapper = new LambdaQueryWrapper<>();
            apUserFanLambdaQueryWrapper.eq(ApUserFan::getUserId, authorId);
            apUserFanLambdaQueryWrapper.eq(ApUserFan::getFansId, user);
            ApUserFan apUserFan = apUserFanMapper.selectOne(apUserFanLambdaQueryWrapper);

            ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery()
                    .eq(ApUserFollow::getUserId, user).eq(ApUserFollow::getFollowId, authorId));

            if(apUserFan!=null||apUserFollow!=null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"已经关注该作者");
            }
            //添加用户关系
            addRelation(authorId, user, apUser);
        }else {
            //取消用户关系
            cancleRelation(authorId, user);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 添加用户关系
     * @param authorId
     * @param user
     * @param apUser
     */
    private void addRelation(Integer authorId, Integer user, ApUser apUser) {
        //拼装userfan实体类
        ApUserFan apUserFan = new ApUserFan();
        apUserFan.setUserId(authorId);
        apUserFan.setFansId(user);
        apUserFan.setFansName(apUser.getName());
        //默认粉丝忠实度设置为正常
        apUserFan.setLevel(FansLevelEnum.NORMALL.getLEVEL());
        apUserFan.setCreatedTime(new Date());
        //默认状态可见
        apUserFan.setIsDisplay(yes);
        //默认屏蔽私信
        apUserFan.setIsShieldLetter(yes);
        //默认展开评论
        apUserFan.setIsShieldComment(no);


        //保存UserFollower数据
        ApUserFollow apUserFollow = new ApUserFollow();
        apUserFollow.setUserId(user);
        apUserFollow.setFollowId(authorId);
        apUserFollow.setFollowName(apUser.getName());
        //默认关注程度为一般(0)
        apUserFollow.setLevel(FollowerLevelEnum.General.getLEVEL());
        //默认动态通知
        apUserFollow.setIsNotice(yes);
        apUserFollow.setCreatedTime(new Date());
        //保存UserFan数据和UserFollower数据
        apUserFanMapper.insert(apUserFan);
        apUserFollowMapper.insert(apUserFollow);
    }

    /**
     * 取消用户关系
     * @param authorId
     * @param user
     */
    private void cancleRelation(Integer authorId, Integer user) {
        //删除UserFan数据和
        LambdaQueryWrapper<ApUserFan> apUserFanLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apUserFanLambdaQueryWrapper.eq(ApUserFan::getUserId, authorId);
        apUserFanLambdaQueryWrapper.eq(ApUserFan::getFansId, user);
        apUserFanMapper.delete(apUserFanLambdaQueryWrapper);
        //删除UserFollower数据
        apUserFollowMapper.delete(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getUserId, user).eq(ApUserFollow::getFollowId, authorId));
    }

    /**
     * 查找用户关系
     * @param articleInfoDto
     * @return
     */
    @Override
    public ResponseResult RelationSearch(ArticleInfoDto articleInfoDto) {
        //作者id
        Long  authorId = articleInfoDto.getAuthorId();
        //获取userID
        Long userId = articleInfoDto.getUserId();

        LambdaQueryWrapper<ApUserFan> apUserFanLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apUserFanLambdaQueryWrapper.eq(ApUserFan::getUserId, authorId);
        apUserFanLambdaQueryWrapper.eq(ApUserFan::getFansId, userId);
        ApUserFan apUserFan = apUserFanMapper.selectOne(apUserFanLambdaQueryWrapper);

        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getUserId, userId).eq(ApUserFollow::getFollowId, authorId));
        if(apUserFollow!=null&&apUserFan!=null){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
    }
}
